
"""
    tcp服务端2.0
"""

import socket


def request_handler(tcp_client, ip_port):
    recv_data = tcp_client.recv(1024)

    # print(recv_data)

    # 判断客户端是否断开连接，但是目前有问题，还不知道怎么解
    if not recv_data:
        print("%s客户端断开连接" % str(ip_port))
        tcp_client.close()
        return

    print(recv_data)

    response_line = "HTTP/1.1 200 OK\r\n"
    response_header = "Server:Python20WS/0.1\r\n"
    response_blank = "\r\n"
    with open("index.html", "r") as file:
        file_data = file.read()

    response_body = file_data

    response_data = response_line + response_header + response_blank + response_body

    tcp_client.send(response_data.encode())
    tcp_client.close()


def init():
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

    tcp_server.bind(("192.168.0.107", 8080))
    tcp_server.listen(128)

    while True:
        new_tcp_client,ip_port = tcp_server.accept()
        print("%s客户端已连接" % str(ip_port))

        request_handler(new_tcp_client, ip_port)

    # tcp_server.close()


if __name__ == '__main__':
    init()
